<script setup lang="ts">
import RoleTable from "./components/Table.vue"
import { onMounted, ref } from "vue"
import { reqRoleAdd, reqRoleList, reqRoleEdit } from "@/api/role/role"
import type {
  RoleParamsTypes,
  RoleResponse,
  RoleResponseData,
  RoleResult,
} from "@/api/types/role"
import { useXlsxDownload } from "@/hooks/export/export"
import { useUploadXlsx } from "@/hooks/import/import"
import {importRoleUrl} from '@/api/uoload/uoloadUrl'

// 当前页
const current = ref<number>(1)
// 请求总条数
const limit = ref<number>(5)
// 总数
const total = ref<number>(0)
// 搜索内容
const searchValue = ref("")
// 角色列表数据
const RoleList = ref<RoleResult[]>([])
// 对话框显示与隐藏
const dialogVisible = ref(false)
// 对话框显示
const dialogRoleForm = ref<RoleResult>({
  roleName: "",
  description: "",
})
// 角色表单实例
const dialogFormRef = ref()
// 对话框表单验证
const dialogFormRules = {
  roleName: [{ required: true, message: "角色昵称必填", tigger: "blur" }],
  description: [{ required: true, message: "角色描述必填", tigger: "blur" }],
}
// 状态控制
const isWhose = ref(1)
// 获取列表数据
const getRolelist = async (pages: number = 1) => {
  current.value = pages
  // 角色列表请求参数
  const RoleListParams: RoleParamsTypes = {
    current: current.value,
    limit: limit.value,
    roleName: searchValue.value.trim(),
  }
  const { data: result }: RoleResponseData = await reqRoleList(RoleListParams)
  // 赋值列表数据
  RoleList.value = result.result
  current.value = Number(result.current)
  limit.value = Number(result.limit)
  total.value = Number(result.total)
}

// 重置搜索内容
const reset = () => {
  searchValue.value = ""
  getRolelist()
}
// 新增角色
const addRole = async () => {
  dialogVisible.value = true
  //   清空上一次数据
  Object.assign(dialogRoleForm.value, {
    roleName: "",
    description: "",
  })
}

// 获取列表数据长度
const handleSizeChange = () => {
  getRolelist()
}

// 对话框隐藏
const handleClose = async () => {
  await dialogFormRef.value.clearValidate()
  dialogVisible.value = false
  dialogRoleForm.value = {
    roleName: "",
    description: "",
  }
}

// 对话框表单取消
const cancelClose = () => {
  handleClose()
}

// 编辑角色子元素方法
const hideEdit = (row: RoleResult) => {
  isWhose.value = 2
  dialogVisible.value = true
  Object.assign(dialogRoleForm.value, row)
}

// 对话框表单提交
const save = async () => {
  // 新增状态下
  if (isWhose.value == 1) {
    await dialogFormRef.value.validate()
    const result: RoleResponse = await reqRoleAdd(dialogRoleForm.value)
    if (result.code == 201) {
      dialogVisible.value = false
      getRolelist(current.value)
      ElMessage.success(result.msg)
      return
    }
    ElMessage.error(result.msg)
  }
  // 编辑状态下
  if (isWhose.value == 2) {
    await dialogFormRef.value.validate()
    const result: RoleResponse = await reqRoleEdit(dialogRoleForm.value)
    if (result.code == 201) {
      await dialogFormRef.value.resetFields()
      dialogVisible.value = false
      getRolelist(current.value)
      ElMessage.success(result.msg)
      return
    }
    ElMessage.error(result.msg)
  }
}

// 角色信息导出
const expresData =()=> {
    const headers =['角色名','角色描述','创建时间','更新时间']
    const exportData = RoleList.value.map((v) =>  {      
        return {
            "角色名":v.roleName,
            "角色描述":v.description,
            "创建时间":v.createTime,
            "更新时间":v.updateTime,
        }
    })    
    useXlsxDownload(headers,exportData,'角色信息')   
}
// 导入数据hooks函数
const {headers,handleSuccess,beforeUpload} =useUploadXlsx(()=> {
    getRolelist(current.value)
})

onMounted(() => {
  // 获取列表数据
  getRolelist()
})
</script>

<template>
  <div class="role">
    <!-- 功能 -->
    <el-card class="use">
      <el-row>
        <el-col :span="8" v-has="`Role.btn.query`">
          <el-input
            v-model="searchValue"
            placeholder="请输入角色昵称"
          ></el-input>
          <el-button
            @click="getRolelist(1)"
            :disabled="searchValue.length > 0 ? false : true"
            type="primary"
            >搜索</el-button
          >
          <el-button
            :disabled="searchValue.length > 0 ? false : true"
            @click="reset"
            type="info"
            >重置</el-button
          >
        </el-col>
        <el-col :span="3">
          <el-button v-has="`Role.btn.Add`" @click="addRole" type="primary">新增角色</el-button>
        </el-col>
        <el-col :span="3" v-has="`Role.btn.import`">
            <el-upload
            class="upload-excel"
            :show-file-list="false"
            name="roleXlsx"
            :headers="headers"
            :action="importRoleUrl"
            :on-success="handleSuccess"
            :before-upload="beforeUpload"
          >
            <el-button  type="success">角色导入</el-button>
          </el-upload>
        </el-col>
        <el-col :span="3">
          <el-button v-has="`Role.btn.export`" @click="expresData" type="info">角色导出</el-button>
        </el-col>

      </el-row>
    </el-card>
    <!-- 数据列表 -->
    <el-card class="list">
      <!-- 角色列表 -->
      <RoleTable
        :RoleList="RoleList"
        :current="current"
        @hideEdit="hideEdit"
        @getRolelist="getRolelist"
      />
      <!-- 分页器 -->
      <el-pagination
        v-model:current-page="current"
        v-model:page-size="limit"
        :page-sizes="[5, 10, 15, 20]"
        :background="true"
        layout="prev, pager, next, jumper, ->,total, sizes"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="getRolelist"
      />
    </el-card>
    <!-- 新增编辑角色 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isWhose == 1 ? '新增角色' : '编辑角色'"
      width="600"
      :before-close="handleClose"
    >
      <template #default>
        <el-form
          :model="dialogRoleForm"
          ref="dialogFormRef"
          :rules="dialogFormRules"
          label-width="80"
        >
          <el-form-item label="角色昵称" prop="roleName">
            <el-input
              v-model="dialogRoleForm.roleName"
              placeholder="请输入角色昵称"
            ></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input
              v-model="dialogRoleForm.description"
              placeholder="请输入角色描述"
            ></el-input>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelClose">取消</el-button>
          <el-button type="primary" @click="save"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.role {
  .use {
    margin-bottom: 20px;
    .el-input {
      width: 140px;
      margin-right: 10px;
    }
  }
  .el-pagination {
    margin-top: 20px;
  }
}
</style>
